package com.future.message.Utils;

import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
public class toZipUtils {

    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[4096];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            log.info("压缩完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args){
        List<File> versionZip=new ArrayList<>();
        //需要压缩文件地址
        versionZip.add(new File("C:\\usr\\src\\index\\static\\upload\\index\\567\\2021年秋季学期返校学生健康信息卡（家长确认书）.xlsx"));
        versionZip.add(new File("C:\\usr\\src\\index\\static\\upload\\index\\567\\197514425cfdb3cae2246b711e1112ce.jpeg"));
        //压缩文件地址以及文件名
        String fileZip="C:\\usr\\test.zip";
        OutputStream os=null;
        try {
            os=new FileOutputStream(new File(fileZip));
            //调用压缩方法
            toZip(versionZip,os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            //关闭流
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
